<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用对象字面量或Map替代Switch语法</title>
  <style>
    *,
    *::after,
    *::before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      min-height: 100vh;
    }

    :root:focus-within {
      scroll-behavior: smooth;
    }

    body {
      min-height: inherit;
    }
  </style>
</head>

<body>
  <div></div>
</body>
<script>
  "use strict"; {
    let print = (color) => {
      switch (color) {
        case "red":
          return ["apple", "strwberry"]
        case "yellow":
          return ["banana", "pineapple"]
        default:
          return []
      }
    }

    console.log(print(null))
    console.log(print("yellow"))

    // 相同的功能使用对象字面量更加清晰的语法

    const Colors = {
      "red": ["apple", "strwberry"],
      "yellow": ["banana", "pineapple"]
    }

    let print1 = (color) => {
      return Colors[color] || []
    }

    console.log(print1(null))
    console.log(print1("yellow"))


    // 使用Map来实现相同的功能
    const colorsMap = new Map()
      .set("red", ["apple", "strwberry"])
      .set("yellow", ["banana", "pineapple"])

    let print2 = (color) => {
      return colorsMap.get(color) || []
    }

    console.log(print2(null))
    console.log(print2("yellow"))

    // 第二种声明时设置Map的初始化

    let print3 = (color) => {
      return new Map([
        ['red', ["apple", "strwberry"]],
        ['yellow', ["banana", "pineapple"]]
      ]).get(color) ?? []
    }
    console.log(print3(null))
    console.log(print3("yellow"))
  };
</script>

</html>